package com.op.parcel.manage.config.security.permission;

import com.op.parcel.manage.config.security.MyUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author xuan🐽
 */
@Slf4j
@Component
public class MyAccessDecisionManager implements AccessDecisionManager {

	/**
	 * 用户是否有此权限
	 *
	 * @param authentication    {@link MyUserDetails#getAuthorities}
	 * @param o                 HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
	 * @param configAttributes  {@link MySecurityMetadataSource#getAttributes}
	 * @throws AccessDeniedException
	 * @throws InsufficientAuthenticationException
	 */
	@Override
	public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
		if (configAttributes == null) {
			return;
		}
		for (ConfigAttribute c : configAttributes) {
			String needPerm = c.getAttribute();
			for (GrantedAuthority ga : authentication.getAuthorities()) {
				if (needPerm.trim().equals(ga.getAuthority())) {
					return;
				}
			}
		}
		throw new AccessDeniedException("抱歉，您没有访问权限");
	}

	@Override
	public boolean supports(ConfigAttribute configAttribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> aClass) {
		return true;
	}
}
